const express = require('express'),
    router = express.Router(),
    mysql = require('./mysql.js'),
    sql = new mysql(),
    Api = require('./api.js'),
    apix = new Api(),
    fs = require('fs');
var qs = require('querystring');
var http = require('http');

router.post('/school/list',(req,res,next) => {
    var cityId=req.body['cityId'];
    apix.getSchoolListByCity(cityId,(result) => {
        res.send(result);
    });
});

router.post('/create',(req,res,next) => {
    var campus_text=req.body['campus_text'];
    var school_text=req.body['school_text'];
    var cityId=campus_text.split("_")[0];
    var cityName=campus_text.split("_")[1];
    var schoolId=school_text.split("_")[0];
    var schoolName=school_text.split("_")[1];
    //中考成绩
    var scoreFile=req.body['score_file'];
    console.log("输入中考成绩："+scoreFile);
    apix.getCityRankintByScort(scoreFile,(result) => {

        //年级排名
        var schoolRanking=req.body['school_ranking'];
        console.log("输入校排名:"+schoolRanking);

        var spar={
            place:schoolRanking,
            cityId:cityId,
            schoolId:schoolId
        };

        //根据校排名 区县 学校获取分数
        apix.getGradeByRankCitySchool(spar,(res1) => {

            console.log(res1[0].grade);
            //获取模拟排名
            apix.getMockRankingByScort(res1[0].grade,(res2) => {
                var data=parseInt((result[0].ranking-res2[0].ranking)/600);
                console.log("测评结果:"+data);

                //保存其中考试成绩
                sql.get("INSERT INTO subject(chinese,mathematics,english,physics,chemical,creature,history,geography,politik,total,school_ranking,city_id,city_name,school_id,school_name,score_file,result) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[req.body.chinese,req.body.mathematics,req.body.english,req.body.physics,req.body.chemical,req.body.creature,req.body.history,req.body.geography,req.body.politik,req.body.total,req.body.school_ranking,cityId,cityName,schoolId,schoolName,req.body.score_file,data],(err,result) => {
                    if(err){
                        console.log(err);
                    }else{
                        apix.getResult(result.insertId,(result) => {
                            res.send(result[0]);
                        });
                    }

                })

            });
        });
    });
});

router.get('/test',(req,res,next) => {
    var post_data = {
        grant_type: "client_credential",
        appid: "wx0af6bb209cdb85e2",
        secret: "abcac5e7dad36ae4462c2261b8c6d033"
    };//这是需要提交的数据


    var content = qs.stringify(post_data);

    var url = 'http://api.weixin.qq.com/cgi-bin/token?' + content;
    console.log("URL：" + url);
var options = {
    host:'api.weixin.qq.com',
    path:'/cgi-bin/token?' + content,
    method:'POST',
    headers:{
        'Content-Type':'application/x-www-form-urlendcoded'
    }
}

var req = http.request(options, function(res){
    res.setEncoding('utf8');
    res.on('data',function(data){
        console.log("data:",data);
    });
});



});
//1、设置api接口,使前端通过ajax可以获取jsapi-sdk;
/*app.get('/wechat/ticket',function (req, res) {
     var page = req.query.page;
      var t = {};
      var url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+appid+'&secret='+appsecret;
        //2、获取access_token;
      request.get(url,function(err, response, body) {
              var token = JSON.parse(body);
          var ticketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + token.access_token + '&type=jsapi';
             //3、获取ticket并且生成随机字符串,时间戳,签名
             request.get(ticketUrl, function(err, response, ticket) {
                      var data = JSON.parse(ticket);
                    var timestamp = parseInt(new Date().getTime() / 1000);
                    t.ticket = data.ticket;
                        t.noncestr = sha1(new Date());
                    t.timestamp = timestamp;
               var string = 'jsapi_ticket=' + t.ticket + '&noncestr=' + t.noncestr + '&timestamp=' + timestamp + '&url=' + page;
               t.signature = sha1(string);
                     res.json(t);
              });
     });
 });*/



module.exports = router;
